const { HTTP } = require('../../utils/http');
const { api } = require('../../utils/api');
const { request } = new HTTP();
const app = getApp();
Component({
  options: {
    multipleSlots: true // 在组件定义时的选项中启用多slot支持
  },
  /**
   * 组件的属性列表
   */
  properties: {
    visible: {
      type: Boolean,
      default: false
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    serviceList: [
      {title: '最实惠', price: 518, duration: 12, mouthPrice: Math.round(518 / 12)},
      {title: '最受欢迎', price: 298, duration: 6, mouthPrice: Math.round(298 / 6)},
      {title: '最便宜', price: 88, duration: 1, mouthPrice: 88},
    ],
    active: 1
  },

  /**
   * 组件的方法列表
   */
  methods: {
    handleTap(e) {
      this.setData({
        active: e.currentTarget.dataset.id,
      });
    },
    close() {
      this.triggerEvent('myClose');
    }, 
    async pay() {
      const self = this;
      wx.showLoading({
        title: '请稍后',
        mask: true,
      });
      const index = this.data.active;
      const params = {
        price: 0.01 || this.data.serviceList[index].price,
        count: 1,
        total_amount: 0.01 * this.data.serviceList[index].price * 1
      }
      const {returnCode = '', bean = {}} = await request({
        url: api.pay,
        method: 'post',
        data: params
      });
      wx.hideLoading();
      if (returnCode === '0000') {
        await wx.requestPayment({
          ...bean,
          success: function(res){
            wx.showToast({
              title: 支付成功,
              icon: 'none',
              duration: 2000,
              success: function() {
                self.triggerEvent('myClose');
                self.triggerEvent('successOpen', {index});
              }
            })
          },
          fail: function(fail){
            // 支付失败
            wx.showToast({
              title: '支付异常',
              icon: 'none',
              duration: 1000,
            });
          },
        });
      }
    }
  }
})
